package com.tmall.testgen.plugin.views;

import java.util.Map;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.tmall.testgen.client.ClientDataCenter;
import com.tmall.testgen.client.commond.InfoReceiveListener;
import com.tmall.testgen.common.bo.interact.back.InterceptInfo;
import com.tmall.testgen.common.util.StringUtil;
import com.tmall.testgen.plugin.views.action.CheckInterceptInfoByCoverAction;
import com.tmall.testgen.plugin.views.action.CheckInterceptInfoByTimeAction;
import com.tmall.testgen.plugin.views.action.CheckModeAction;
import com.tmall.testgen.plugin.views.action.ClearAction;
import com.tmall.testgen.plugin.views.action.GenCodeAction;
import com.tmall.testgen.plugin.views.action.PauseAction;
import com.tmall.testgen.plugin.views.action.RefreshAction;
import com.tmall.testgen.plugin.views.action.StartAction;
import com.tmall.testgen.plugin.views.action.StopAction;
import com.tmall.testgen.plugin.views.vo.TreeParent;
import com.tmall.testgen.plugin.views.vo.ViewContentProvider;
import com.tmall.testgen.plugin.views.vo.ViewLabelProvider;

/**
 * This sample class demonstrates how to plug-in a new workbench view. The view
 * shows data obtained from the model. The sample creates a dummy model on the
 * fly, but a real implementation would connect to the model available either in
 * this or another plug-in (e.g. the workspace). The view is connected to the
 * model using a content provider.
 * <p>
 * The view uses a label provider to define how model objects should be
 * presented in the view. Each view can present the same model objects using
 * different labels and icons, if needed. Alternatively, a single label provider
 * can be shared between views in order to ensure that objects of the same type
 * are presented in the same way everywhere.
 * <p>
 */

public class GenCodeMonitorView extends ViewPart implements InfoReceiveListener {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "com.tmall.testgen.plugin.views.GenCodeMonitorView";

	private TreeViewer viewer;
	public TreeViewer getViewer() {
		return viewer;
	}

	public void setViewer(TreeViewer viewer) {
		this.viewer = viewer;
	}

	private DrillDownAdapter drillDownAdapter;
	/**
	 * 开始拦截
	 */
	private StartAction startAction;
	/**
	 * 暂停拦截
	 */
	private PauseAction pauseAction;
	/**
	 * 停止拦截
	 */
	private StopAction stopAction;
//	/**
//	 * 刷新
//	 */
//	private Action refreshAction;
	/**
	 * 清空
	 */
	private ClearAction clearAction;
	private Action checkModeAction;
	/**
	 * 生成代码
	 */
	private Action genCodeAction;
	private Action doubleClickAction;
	
	/**
	 * 覆盖维度查看视图
	 */
	private CheckInterceptInfoByCoverAction checkInterceptInfoByCoverAction;
	/**
	 * 时间维度查看视图
	 */
	private CheckInterceptInfoByTimeAction checkInterceptInfoByTimeAction;
	private TreeParent root;
	private Display display;
	
	public static  boolean ischeckInterceptInfoByTime=false;


	


	/**
	 * The constructor.
	 */
	public GenCodeMonitorView() {
		root = new TreeParent("");
		
		ClientDataCenter.getInstance().setListener(this);
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	ViewContentProvider p;

	public void createPartControl(Composite parent) {
		display = parent.getDisplay();
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);

		p = new ViewContentProvider();
		viewer.setContentProvider(p);
		viewer.setLabelProvider(new ViewLabelProvider());
		// viewer.setSorter(new NameSorter());
		// viewer.setInput(getViewSite());
		viewer.setInput(root);

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem()
				.setHelp(viewer.getControl(), "testgen.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
		if(!ClientDataCenter.getInstance().isStart()){
			this.beginMonitor(false);
		}
		
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				GenCodeMonitorView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(startAction);
		manager.add(pauseAction);
		manager.add(stopAction);
		//manager.add(refreshAction);
		manager.add(clearAction);
		manager.add(genCodeAction);
		
		
//		manager.add(checkInterceptInfoByCoverAction);
//		manager.add(checkInterceptInfoByTimeAction);
		
		
		MenuManager checkModeManager = new MenuManager("查看拦截方式");
		checkModeManager.add(checkInterceptInfoByCoverAction);
		checkModeManager.add(checkInterceptInfoByTimeAction);
		manager.add(checkModeManager);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(startAction);
		manager.add(pauseAction);
		manager.add(stopAction);
		//manager.add(refreshAction);
		manager.add(clearAction);
		manager.add(genCodeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
		
		MenuManager checkModeManager = new MenuManager("查看拦截方式");
		checkModeManager.add(checkInterceptInfoByCoverAction);
		checkModeManager.add(checkInterceptInfoByTimeAction);
		manager.add(checkModeManager);
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(startAction);
		manager.add(pauseAction);
		manager.add(stopAction);
		//manager.add(refreshAction);
		manager.add(clearAction);
		manager.add(checkModeAction);
		manager.add(genCodeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		checkModeAction.setMenuCreator(new TestMenuCreator());
	}

	private void makeActions() {
		TreeParent interceptRoot = new TreeParent("拦截");
		interceptRoot.setLeafNode(false);
		root.addChild(interceptRoot);
		
//		TreeParent mockRoot = new TreeParent("Mock");
//		mockRoot.setLeafNode(false);
//		root.addChild(mockRoot);
		
		
		startAction = new StartAction(this);
		pauseAction = new PauseAction(this);
		stopAction = new StopAction(this);
		stopAction.setInterceptRoot(interceptRoot);
		//refreshAction = new RefreshAction(this);
		clearAction = new ClearAction();
		clearAction.setInterceptRoot(interceptRoot);
		//clearAction.setMockRoot(mockRoot);
		clearAction.setViewer(viewer);
		checkModeAction = new CheckModeAction();
		genCodeAction = new GenCodeAction();

		
		checkInterceptInfoByCoverAction=new CheckInterceptInfoByCoverAction();
		checkInterceptInfoByCoverAction.setInterceptRoot(interceptRoot);
		//checkInterceptInfoByCoverAction.setMockRoot(mockRoot);
		checkInterceptInfoByCoverAction.setViewer(viewer);
		
		checkInterceptInfoByTimeAction=new CheckInterceptInfoByTimeAction();
		checkInterceptInfoByTimeAction.setInterceptRoot(interceptRoot);
		//checkInterceptInfoByTimeAction.setMockRoot(mockRoot);
		checkInterceptInfoByTimeAction.setViewer(viewer);
		
		
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				if (obj instanceof TreeParent) {
					TreeParent node = (TreeParent) obj;
					//node.setLeafNode(!node.isLeafNode);
					node.addFieldValue();
					viewer.refresh();
				}
			}
		};
		
		if(ClientDataCenter.getInstance().isStart()){
			this.beginMonitor(true);
		}
		
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

	private void showMessage(String message) {
		MessageDialog.openInformation(viewer.getControl().getShell(),
				"单元测试生成-拦截监控", message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}

	public void refreshTree(){
	    
	    display.syncExec(new Runnable() {
            @Override
            public void run() {
                if(ischeckInterceptInfoByTime){
                    checkInterceptInfoByTimeAction.run();
                }else{
                    checkInterceptInfoByCoverAction.run();
                }
            }
        });

	    
	}
	@Override
	public void addInterceptInfo(final InterceptInfo info) {
		//final TreeParent testNode = info2tree(info);
		display.syncExec(new Runnable() {
			@Override
			public void run() {
				if(ischeckInterceptInfoByTime){
					checkInterceptInfoByTimeAction.addInterceptInfo(info);
				}else{
					checkInterceptInfoByCoverAction.addInterceptor(info);
				}

			}
		});

	}

	@Override
	public void actionChecked(Action selectAction) {
		String selectedActionId = selectAction.getId();
		boolean isChecked = selectAction.isChecked();
		if (StartAction.ID.equals(selectedActionId)) {
			stopAction.changeChecked(!isChecked);
			pauseAction.changeChecked(!isChecked);
		} else if (StopAction.ID.equals(selectedActionId)) {
			startAction.changeChecked(!isChecked);
			pauseAction.changeChecked(!isChecked);
		} else if (PauseAction.ID.equals(selectedActionId)) {
			startAction.changeChecked(!isChecked);
			stopAction.changeChecked(!isChecked);
		}
	}
	
	public void beginMonitor(boolean enabled){
		
		startAction.changeChecked(!enabled);
		pauseAction.setEnabled(enabled);
		stopAction.setEnabled(enabled);
		clearAction.setEnabled(enabled);
		genCodeAction.setEnabled(enabled);
		
		if(enabled)
			startAction.changeChecked(enabled);
			
	}
	 //为工具栏中的选项增加下拉菜单
    class TestMenuCreator implements IMenuCreator{  
     private MenuManager dropDownMenuMgr;   
     public Menu getMenu(Menu parent) {//在菜单栏被调用  
            return null;
     }  
       
     public Menu getMenu(Control parent) {//在工具栏被 调用  
         createDropDownMenuMgr();   
         return dropDownMenuMgr.createContextMenu(parent);  
     }  
       
     public void dispose() {  
         if(null != dropDownMenuMgr){  
             dropDownMenuMgr.dispose();  
             dropDownMenuMgr = null;  
         }  
     }  
       
     private void createDropDownMenuMgr() {        
         if (dropDownMenuMgr == null) {            
             dropDownMenuMgr = new MenuManager();                          
             dropDownMenuMgr.add(checkInterceptInfoByCoverAction);
             dropDownMenuMgr.add(checkInterceptInfoByTimeAction);
             }     
         }       
 }
    
    
    
    
    
}